
#include <material_editor/selectmaterialdatadialog.h>
#include <config.h>



SelectMaterialDataDialog::SelectMaterialDataDialog(QWidget *parent)
  : QDialog(parent)
  , _data (0)
{
  _gui.setupUi (this);

  _model = new MaterialDataListModel ();

  _filterProxy = new QSortFilterProxyModel(this);
  _filterProxy->setSourceModel(_model);
  _filterProxy->setDynamicSortFilter(true);
  _filterProxy->setFilterCaseSensitivity(Qt::CaseInsensitive);

  _gui.listViewMaterialData->setModel(_filterProxy);
  _gui.pushButtonOk->setEnabled(false);

  setWindowTitle(CE_TOOL_NAME);

  connect (_gui.pushButtonOk,     SIGNAL(clicked()), this, SLOT(accept()));
  connect (_gui.pushButtonCancel, SIGNAL(clicked()), this, SLOT(reject()));

  connect (_gui.listViewMaterialData->selectionModel(), SIGNAL(currentChanged(QModelIndex,QModelIndex)),
           this, SLOT(SelectionChanged(QModelIndex, QModelIndex)));

  // per default not visible
  SetClearButtonVisible(false);
}


void SelectMaterialDataDialog::SetDelegator(MaterialDataDelegator *delegator)
{
  _delegator = delegator;
  _model->SetDelegator(_delegator);
}

void SelectMaterialDataDialog::on_pushButtonClear_clicked ()
{
  _data = 0;
  accept();
}

void SelectMaterialDataDialog::SetClearButtonVisible(bool visible)
{
  _gui.pushButtonClear->setVisible (visible);
}

void SelectMaterialDataDialog::on_listViewMaterialData_doubleClicked(QModelIndex index)
{
  if (index.isValid())
    {
      QModelIndex srcIndex = _filterProxy->mapToSource(index);
      if (srcIndex.isValid())
        {
          _data = _delegator->GetMaterialData(srcIndex.row());
          accept();
        }
    }
}

void SelectMaterialDataDialog::on_lineEditFilter_textChanged(const QString &text)
{
  _filterProxy->setFilterFixedString(text);
}

void SelectMaterialDataDialog::SelectionChanged (QModelIndex index, QModelIndex)
{
  if (index.isValid())
    {
      QModelIndex srcIndex = _filterProxy->mapToSource(index);
      if (srcIndex.isValid())
        {
          _data = _delegator->GetMaterialData(srcIndex.row());
        }
    }

  _gui.pushButtonOk->setEnabled(index.isValid());
}

MaterialData* SelectMaterialDataDialog::GetData()
{
  return _data;
}
